<script setup lang="ts">
import { computed, ref, unref, useAttrs } from 'vue';
import type { DataTableColumns, DataTableRowKey } from 'naive-ui';
import { useMessage } from 'naive-ui';
import { useTable, useTableOperate } from '@/hooks/common/table';
import type { FormProps } from '@/components/form/props';
import Form from '../form/index.vue';
interface IProps {
  // 批量删除API，参数为ID数组，返回删除结果
  batchDeleteApi?: (ids: DataTableRowKey[]) => Promise<unknown>;
  getTableDataApi: (
    params: Pick<Api.Common.PaginatingCommonParams, 'current' | 'size'>
  ) => Promise<NaiveUI.FlatResponseData<Api.Common.PaginatingQueryRecord<any>>>;
  title?: string;
  tableColumns?: DataTableColumns<{ id: string | number; name: string }>;
  useForm?: boolean;
  formConfig?: FormProps; // 表单配置，传入则显示表单
}
const attrs = useAttrs();
const props = withDefaults(defineProps<IProps>(), {
  useForm: true,
  formConfig: () => {
    return {
      formItems: [],
      labelPlacement: 'left',
      modelValue: {},
      rules: {},
      size: 'medium',
      labelWidth: 80,
      inline: true,
      formGrid: {
        span: 18
      }
    };
  },
  title: '',
  tableColumns: () => [],
  batchDeleteApi: undefined
});
const expandedNames = ref(['1']);
const collapseTitle = ref('收起');
const message = useMessage();
const { batchDeleteApi, getTableDataApi, useForm, formConfig, tableColumns } = props;

// 表格配置
const tableConfig = {
  apiFn: getTableDataApi,
  apiParams: {
    current: 1,
    size: 10
  } as Api.Common.PaginatingCommonParams,
  columns: () => {
    return tableColumns;
  },
  showTotal: true
};

// 使用表格Hook
const { loading, data, columns, pagination, searchParams, updateSearchParams, resetSearchParams, getData } =
  useTable(tableConfig);

// 使用操作Hook
const { checkedRowKeys, onBatchDeleted } = useTableOperate(data, getData);

// 搜索处理
const handleSearch = (val: any) => {
  const newVal = { ...searchParams, ...val };
  Object.keys(newVal).forEach(key => {
    if (newVal[key] === '') {
      newVal[key] = undefined;
    }
  });
  updateSearchParams({
    ...newVal,
    current: 1 // 搜索时重置到第一页
  });
  getData();
};

const operationColumns = computed(() => {
  const arr = unref(columns);
  return arr.map(row => {
    const { key, title = '', ...obj } = row as { key: string; title: string };
    return {
      ...obj,
      title,
      key: key as string,
      checked: true
    };
  });
});

const abc = ref(unref(operationColumns));

const showColumns = computed(() => {
  return abc.value.filter(row => row.checked);
});

function handleExpanded(names: string[]) {
  collapseTitle.value = names.length > 0 ? '收起' : '展开';
}

// 处理批量删除
const handleBatchDelete = async () => {
  if (checkedRowKeys.value.length <= 0) {
    message.error('请选择要删除的项');
    return;
  }
  await onBatchDeleted();
  if (!batchDeleteApi) {
    return;
  }
  await batchDeleteApi(checkedRowKeys.value);
};

// 表格勾选回调
function handleCheckedRowKeysChange(checkedRows: DataTableRowKey[]) {
  checkedRowKeys.value = checkedRows;
}

const emit = defineEmits<{
  (e: 'add'): void;
}>();

function handleAdd() {
  emit('add');
}

defineExpose({
  refreshList() {
    getData();
  }
});

// 处理表单提交
</script>

<template>
  <div class="table-container">
    <!-- 搜索区域 -->
    <!--
 <div class="search-bar">
      <NInput v-model:value="searchParams.keyword" placeholder="请输入关键词" />
      <NButton @click="handleSearch">搜索</NButton>
      <NButton @click="resetSearchParams">重置</NButton>
      <NButton type="primary" @click="handleAdd">新增</NButton>
    </div>
-->
    <NCard v-if="useForm" size="small" class="mb-4">
      <NCollapse v-model="expandedNames" :default-expanded-names="['1']" @update:expanded-names="handleExpanded">
        <NCollapseItem :title="collapseTitle" name="1">
          <Form v-bind="formConfig" :loading="loading" @submit="handleSearch" @reset="resetSearchParams" />
        </NCollapseItem>
      </NCollapse>
    </NCard>

    <NCard :title="title" size="small">
      <template #header-extra>
        <TableHeaderOperation
          v-model:columns="abc"
          :disabled-delete="attrs['disabled-delete'] ? true : false"
          :disabled-add="attrs['disabled-add'] ? true : false"
          @add="handleAdd"
          @refresh="getData"
          @delete="handleBatchDelete"
        />
      </template>
      <!-- <NDataTable v-bind="rest" :pagination="pagination" /> -->
      <!-- 加载状态 -->
      <!-- <NLoadingBar v-if="loading" :active="loading" :height="4" /> -->

      <!-- 原生表格组件，透传所有属性和事件 -->
      <NDataTable
        :columns="showColumns as DataTableColumns<any>"
        :data="data"
        :loading="loading"
        :row-key="row => row.id"
        @update:checked-row-keys="handleCheckedRowKeysChange"
      />
      <NGrid x-gap="12" :cols="1" class="pt-5">
        <NGi class="flex justify-end">
          <NPagination v-bind="pagination" :show-size-picker="true" />
        </NGi>
      </NGrid>
    </NCard>
    <!-- 批量删除按钮 -->
    <!-- <NButton danger :disabled="checkedRowKeys.length === 0" @click="handleBatchDelete">批量删除</NButton> -->
  </div>
</template>
